package mysql

import (
	"database/sql"
	"news/common"
	"news/constStatus"
	"news/models"
)

// 检查注册的用户是否存在
func CheckUserExit(username string) (err error) {
	var count int
	sqlStr := "select count(user_id) from user where username = ? "
	err = db.Get(&count, sqlStr, username)
	if err != nil {
		return constStatus.ErrorNOTTable
	}
	if count > 0 {
		return constStatus.ErrorUserExist
	}
	return
}

// user 用户注册信息保存数据库
func InsertUser(user *models.User) (err error) {
	user.Password = common.EncryptPassword(user.Password)
	sqlStr := "insert into user(user_id ,username,password) values(?,?,?)"
	_, err = db.Exec(sqlStr, user.UserID, user.Username, user.Password)
	return err
}

// login 用户登录模块
func Login(user *models.User) (err error) {
	//获取用户登录密码 ,并加密与数据库密码进行匹配
	oPassword := common.EncryptPassword(user.Password)
	sqlStr := `select user_id,username,password from user where username = ?`
	err = db.Get(user, sqlStr, user.Username)
	if err == sql.ErrNoRows {
		return constStatus.ErrorUserNotExist
	}
	if err != nil {
		return constStatus.ErrorNOTTable
	}
	if oPassword != user.Password {
		return constStatus.ErrorInvalidPassword
	}
	return
}

// 通过ID  获取User 的作者名称
func GetUserByID(idStr int64) (user *models.User, err error) {
	user = new(models.User)
	sqlStr := `select user_id, username from user where user_id = ?`
	err = db.Get(user, sqlStr, idStr)
	return
}
